/**
 * 
 */
package com.woupla.city;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;

import com.woupla.model.Region;

/**
 * @author dimi
 * 
 */
@RequestScoped
@FacesConverter(value = "RegionConverter", forClass = Region.class)
public class RegionConverter implements Converter {

	@Inject
	private CityEJB cityEJB;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		Region region = new Region();
		if (value.trim().equals("")) {
			return null;
		} else {
			try {
				System.out.println("Value Objet " + region.getLabel());
				region = cityEJB.findRegionLabel(value);
				if (region == null)
					new FacesMessage(
							FacesMessage.SEVERITY_ERROR, "Conversion Error",
							"Not a valid region");
			} catch (NumberFormatException exception) {
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Conversion Error",
						"Not a valid region"));
			}
		}
		System.out.println("Objet " + region.getLabel());
		return region;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		String retour = "";
		if (value instanceof Region) {
			Region region = (Region) value;
			if (region.getLabel() != null)
				retour = region.getLabel();
			System.out.println("String " + retour);
		}

		return retour;
	}

}
